package com.time.company.components;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TabHost;
import android.widget.TextView;


import com.google.gson.Gson;
import com.sina.weibo.sdk.share.WbShareCallback;
import com.sina.weibo.sdk.share.WbShareHandler;
import com.time.company.R;
import com.time.company.app.AddressManager;
import com.time.company.base.BaseActivity;
import com.time.company.base.BasePW;
import com.time.company.common.event.BaseEvent;
import com.time.company.components.compose.ApplyActivity;
import com.time.company.components.compose.ComposeFragment;
import com.time.company.components.compose.EditActivity;
import com.time.company.components.discovery.DiscoveryFragment;
import com.time.company.components.dynamics.DynamicsFragment;
import com.time.company.components.popup.PublishPW;
import com.time.company.components.profile.ProfileFragment;
import com.time.company.components.task.TaskFragment;
import com.time.company.servermodel.BasicBean;
import com.time.company.servermodel.MyVersion;
import com.time.company.utils.DownloadUtils;
import com.time.company.utils.JpushUtils;
import com.time.company.utils.NetWorkUtils;
import com.time.company.utils.ToastUtils;
import com.time.company.views.MyFragmentTabHost;
import com.time.company.webserver.helper.WebServerManager;
import com.time.company.webserver.request.BasicRequest;
import com.time.company.webserver.request.requestsParamters.LoginParameters;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.ArrayList;
import java.util.List;

import cn.jpush.android.api.JPushInterface;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;

public class MainActivity extends BaseActivity implements TabHost.OnTabChangeListener, WbShareCallback {

    public static final String EXTRA_REGISTER_AWARD = "extra_register_award";
    private static final int VERSION_COMPARE = 1;

    private List<TabItem> tabItemList;
    private MyFragmentTabHost fragmentTabHost;

    // Sina share
    public WbShareHandler shareHandler;

    public static void start(Activity activity) {
        Intent intent = new Intent(activity, MainActivity.class);
        activity.startActivity(intent);
    }

    public static void start(Activity activity, String regAward) {
        Intent intent = new Intent(activity, MainActivity.class);
        intent.putExtra(EXTRA_REGISTER_AWARD, regAward);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        initTabData();
        initTabHost();
        findView(R.id.iv_main_center).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAddPw();
            }
        });

        // Init sina share
        shareHandler = new WbShareHandler(this);
        shareHandler.registerApp();

        andPermission(100, new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE});
    }

    @Override
    public void onResume() {
        super.onResume();
        JPushInterface.resumePush(this);
        JPushInterface.onResume(this);
    }

    /**
     * 初始化Tab数据
     */
    private void initTabData() {
        tabItemList = new ArrayList<>();
        //添加任务Tab
        tabItemList.add(new TabItem(R.drawable.tabbar_task, R.drawable.tabbar_task_select,
                R.string.tab_task_title, TaskFragment.class));
        //添加发现公益Tab
        tabItemList.add(new TabItem(R.drawable.tabbar_dicovery, R.drawable.tabbar_dicovery_select,
                R.string.tab_discovery_title, DiscoveryFragment.class));
        //添加发布Tab
        tabItemList.add(new TabItem(R.drawable.tabbar_compose_button
                , R.drawable.tabbar_compose_button_highlighted, 0, ComposeFragment.class));
        //添加动态Tab
        tabItemList.add(new TabItem(R.drawable.tabbar_dynamics, R.drawable.tabbar_dynamics_select,
                R.string.tab_dynamics_title, DynamicsFragment.class));
        //添加我的Tab
        tabItemList.add(new TabItem(R.drawable.tabbar_profile, R.drawable.tabbar_profile_select,
                R.string.tab_profile_title, ProfileFragment.class));
    }

    /**
     * 初始化主页选项卡视图
     */
    private void initTabHost() {
        //获取FragmentTabHost
        fragmentTabHost = findView(android.R.id.tabhost);
        //绑定TabHost（绑定我们的body）
        fragmentTabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
        //去掉TabHost分割线
        fragmentTabHost.getTabWidget().setDividerDrawable(null);

        int size = tabItemList.size();
        for (int i = 0; i < size; i++) {
            TabItem tabItem = tabItemList.get(i);
            //将Fragment添加到FragmentTabHost组件上面
            //newTabSpec 代表是Tab名字
            //indicator 代表是Tab图片
            TabHost.TabSpec tabSpec = fragmentTabHost
                    .newTabSpec(tabItem.getTitleStr())
                    .setIndicator(tabItem.getView());
            //添加Fragment
            fragmentTabHost.addTab(tabSpec, tabItem.getFragmentClass(), tabItem.getBundle());
            //给Tab按钮设置背景色
            fragmentTabHost.getTabWidget()
                    .getChildAt(i)
                    .setBackgroundColor(ContextCompat.getColor(this, R.color.white));
            //监听点击的Tab
            fragmentTabHost.setOnTabChangedListener(this);
            //默认选中第一个Tab
            if (i == 0) {
                tabItem.setCheck(true);
            }
        }
    }

    private int index = 0;

    @Override
    public void onTabChanged(String tabTitle) {
        if (TextUtils.isEmpty(tabTitle)) {
            // 表示没有title的Tab， 一般是中间按钮，此处没有
            index = 2;
            fragmentTabHost.setCurrentTab(index);
            return;
        }

        if (TextUtils.equals(tabTitle, getString(R.string.tab_task_title))) {
            index = 0;
            changeTabItem(true, false, false, false);
            EventBus.getDefault().post(new BaseEvent(getString(R.string.refresh_task_fragment_data)));
        } else if (TextUtils.equals(tabTitle, getString(R.string.tab_discovery_title))) {
            index = 1;
            changeTabItem(false, true, false, false);
        } else if (TextUtils.equals(tabTitle, getString(R.string.tab_dynamics_title))) {
            index = 3;
            changeTabItem(false, false, true, false);
        } else if (TextUtils.equals(tabTitle, getString(R.string.tab_profile_title))) {
            index = 4;
            changeTabItem(false, false, false, true);
        }
    }

    private void showAddPw() {
        if (publishPW == null || !publishPW.isShowing()) {
            launchPublish();
        }
    }

    private void changeTabItem(boolean one, boolean two, boolean three, boolean four) {
//        if (application.isLogin()) {
        fragmentTabHost.setCurrentTab(index);
        tabItemList.get(0).setCheck(one);
        tabItemList.get(1).setCheck(two);
        tabItemList.get(3).setCheck(three);
        tabItemList.get(4).setCheck(four);
//        } else {
//            if (index != 0) {
//                fragmentTabHost.setCurrentTab(0);
//                LoginActivity.start(this);
//            }
//        }
    }

    /**
     * 代表每一个Tab
     */
    class TabItem {
        // 正常情况下显示的图片
        private int imageNormal;
        // 选中情况下显示的图片
        private int imagePress;

        // Tab的名字
        private int title;
        private String titleStr;
        private Class<? extends Fragment> fragmentClass;

        private View view;
        private ImageView imageView;
        private TextView textView;
        private Bundle bundle;

        public TabItem(int imageNormal, int imagePress, int title, Class<? extends Fragment> fragmentClass) {
            this.imageNormal = imageNormal;
            this.imagePress = imagePress;
            this.title = title;
            this.fragmentClass = fragmentClass;
        }

        public int getImageNormal() {
            return imageNormal;
        }

        public int getImagePress() {
            return imagePress;
        }

        public int getTitle() {
            return title;
        }

        public String getTitleStr() {
            if (title == 0) {
                return "";
            }
            if (TextUtils.isEmpty(titleStr)) {
                titleStr = getString(title);
            }
            return titleStr;
        }

        public Class<? extends Fragment> getFragmentClass() {
            return fragmentClass;
        }

        // 切换Tab， 改变Tab样式
        public Bundle getBundle() {
            if (bundle == null) {
                bundle = new Bundle();
            }
            bundle.putString("title", getTitleStr());
            return bundle;
        }

        public void setCheck(boolean isChecked) {
            if (imageView != null) {
                if (isChecked) {
                    imageView.setImageResource(imagePress);
                } else {
                    imageView.setImageResource(imageNormal);
                }
            }
            if (textView != null && title != 0) {
                if (isChecked) {
                    textView.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.black_x));
                } else {
                    textView.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.color_main_tab_indicator_title));
                }
            }
        }

        public View getView() {
            if (view == null) {
                int layoutId = 0;
                if (title == 0) {
                    // 当title为0的时候表示没有标题，只有图标，一般是中的按钮
                    layoutId = R.layout.main_tab_publish_indicator;
                } else {
                    layoutId = R.layout.main_tab_indicator;
                }
                view = getLayoutInflater().inflate(layoutId, null);
                imageView = (ImageView) view.findViewById(R.id.tab_img);
                imageView.setImageResource(imageNormal);
                // 判断资源是否存在
                if (title != 0) {
                    textView = (TextView) view.findViewById(R.id.tab_tv);
                    textView.setText(getTitleStr());
                }
            }
            return view;
        }
    }

    @Override
    public void onBackPressed() {
        doubleClickExit();
    }

    private long exitTime = 0;

    /**
     * 双击退出程序
     */
    private void doubleClickExit() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            ToastUtils.showShort(getString(R.string.double_exit_app));
            exitTime = System.currentTimeMillis();
        } else {
            application.exitApp();
            finish();
            super.onBackPressed();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // TODO: 2017/10/25
        if (null != shareHandler) {
            shareHandler.doResultIntent(intent, this);
        }

        if (!TextUtils.isEmpty(intent.getStringExtra(getString(R.string.tab_title)))) {
            String title = intent.getStringExtra(getString(R.string.tab_title));
            if (TextUtils.equals(title, getString(R.string.tab_task_title))) {
                fragmentTabHost.setCurrentTab(0);
            } else if (TextUtils.equals(title, getString(R.string.tab_discovery_title))) {
                fragmentTabHost.setCurrentTab(1);
            } else if (TextUtils.equals(title, getString(R.string.tab_dynamics_title))) {
                fragmentTabHost.setCurrentTab(3);
                EventBus.getDefault().post(new BaseEvent(application.getString(R.string.refresh_dynamics_fragment_data)));
            } else if (TextUtils.equals(title, getString(R.string.tab_profile_title))) {
                fragmentTabHost.setCurrentTab(4);
                EventBus.getDefault().post(new BaseEvent(application.getString(R.string.refresh_profile_fragment_data)));
            } else {
                return;
            }
        }

    }

    @Override
    public void onWbShareSuccess() {
//        ToastUtils.showLong("分享成功");
    }

    @Override
    public void onWbShareCancel() {
    }

    @Override
    public void onWbShareFail() {
//        ToastUtils.showLong("分享失败");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 404: {
                // 用户从设置中回来，无论有没有开启所需要的权限
//                ToastUtils.showShort("从设置中回来");
                break;
            }
        }
    }

    @Subscribe
    public void onEventMainThread(BaseEvent event) {
        if (TextUtils.isEmpty(event.getBaseType())) {
            return;
        }
        if (TextUtils.equals(event.getBaseType(), getString(R.string.tab_discovery_title))) {
            fragmentTabHost.setCurrentTab(1);
        }
    }

    private WindowManager.LayoutParams attributes;
    private PublishPW publishPW;

    private void launchPublish() {
        final Window window = this.getWindow();
        attributes = window.getAttributes();
        attributes.alpha = 0.5f;
        window.setAttributes(attributes);
        publishPW = new PublishPW(this, fragmentTabHost);
        publishPW.setOnItemClickListener(new BasePW.OnItemClickListener() {
            @Override
            public void onItemClick(int type, Object result) {
                if (type == resources.getInteger(R.integer.pw_compose_one)) {
                    // 志愿申请
                    ApplyActivity.start(MainActivity.this);
                } else {
                    // 动态发布
                    EditActivity.start(MainActivity.this, "main");
                }
            }
        });
        publishPW.showAtLocation(fragmentTabHost, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        publishPW.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                attributes.alpha = 1.0f;
                window.setAttributes(attributes);
            }
        });
    }

    private void andPermission(int requestCode, String[] permissions) {
        AndPermission.with(this)
                .requestCode(requestCode)
                .permission(permissions)
                .callback(listener)
                // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                // 这样避免用户勾选不再提示，导致以后无法申请权限。
                // 你也可以不设置。
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(MainActivity.this, rationale)
                                .show();
                    }
                })
                .start();
    }

    // 权限回调监听
    PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            if (requestCode == 100) {
                // 表示定位的权限申请通过
                versionCompare();
            }

        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            if (requestCode == 100) {
                // 即使是用户选择了不在询问还是会toast该提示语
                ToastUtils.showShort("请开启你的定位权限");
            }

            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
            if (AndPermission.hasAlwaysDeniedPermission(MainActivity.this, deniedPermissions)) {
                // 第一种：用默认的提示语。
                AndPermission.defaultSettingDialog(MainActivity.this, 404).show();

            }

        }
    };


    /**
     * 版本检查
     */
    private void versionCompare() {
        if (NetWorkUtils.isNetAvailable(this)) {
            Request request = new BasicRequest(AddressManager.getInstance().getAddress());
            LoginParameters parameters = new LoginParameters();
            parameters.setCommand(getString(R.string.command_versionCompare));
            parameters.setUserId(!TextUtils.isEmpty(application.getAccount()) ? application.getAccount() : "");
            parameters.setUserType(getString(R.string.user_type_person));
            parameters.setNum(JpushUtils.getVersionCode(this) + "");
            request.add(getString(R.string.command), parameters.getCommand());
            request.add(getString(R.string.platform), parameters.getPlatform());
            request.add(getString(R.string.data), new Gson().toJson(parameters));
            request.setCancelSign(toString());
            WebServerManager.getInstance().add(this, request, this, VERSION_COMPARE,
                    true, true, true);
        } else {
            ToastUtils.showShort(getString(R.string.network_error));
        }
    }

    @Override
    public void onSucceed(int what, Response<BasicBean> response) {
        BasicBean basicBean = response.get();
        if (basicBean == null) return;

        if (basicBean.isSuccess()) {
            MyVersion version = basicBean.parseData(MyVersion.class);
            if (version == null) return;
            if (!TextUtils.isEmpty(version.getNum())) {
                if (JpushUtils.getVersionCode(this) < Integer.parseInt(version.getNum())) {
                    // 静默更新
                    if (NetWorkUtils.isWifi(this)) {
                        DownloadUtils.getInstance().downLoadApk(this, version.getPath());
                    }
                }
            }


        } else {
            ToastUtils.showShort(basicBean.getMsg());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

        if (null != publishPW) {
            publishPW.dismiss();
            publishPW = null;
        }
    }
}
